//
//  SearchAction.swift
//  MagaCore
//
//  Created by MrMessy on 2023/5/14.
//

import Foundation
import ReSwift
import ReSwiftThunk
import Moya
import HandyJSON
import PKHUD
import Alamofire

enum HTEnumSearchAction: Action {
  case htEnumPopulars(var_populars: [HTSearchPopular]?)
  case htEnumSearchList(var_searchAnimes: [HTAnime]?)
  case htEnumSearchHistory(var_searchHistory: [String]?)
  
  // 获取热搜词
  static func ht_populars(callback: (([HTSearchPopular]) -> Void)?) -> Thunk<HTAppState> {
    Thunk<HTAppState> { dispatch, _ in
      HTNetworkManager().ht_request(.htEnumPopularList(var_type: "pop")) { (result) in
        let var_data = result.ht_data()
        let var_populars = [HTSearchPopular].deserialize(from: var_data) as? [HTSearchPopular]

        if (callback != nil) {
          callback!(var_populars!)
        }

        dispatch(HTEnumSearchAction.htEnumPopulars(var_populars: var_populars))
      }
    }
  }

  // 获取搜索列表信息
  static func ht_searchList(params: [String: String], andCallback: (([HTAnime]?) -> Void)?) -> Thunk<HTAppState> {
    Thunk<HTAppState> { dispatch, _ in
      HTNetworkManager().ht_request(.htEnumSearch(var_keyword: params["keyword"] ?? "", var_page: params["page"] ?? "", var_page_size: params["page_size"] ?? "", var_p1: "1")) { (result) in
        let var_data = result.ht_data()
        let var_searchAnimes = [HTAnime].deserialize(from: var_data, designatedPath: "list") as? [HTAnime]

        if (andCallback != nil) {
          andCallback!(var_searchAnimes ?? [])
        }
      }
    }
  }

  // 搜索联想词
  static func ht_searchAssociationalWord(keyword: String, andCallback: (([String]?) -> Void)?) -> Thunk<HTAppState> {
    Thunk<HTAppState> { dispatch, _ in
      let url = "https://suggestqueries.google.com/complete/search"
      let parameters: Parameters = [
        "client": "youtube",
        "q": keyword
      ]

      AF.request(url, parameters: parameters).responseString { response in
        switch response.result {
        case .success(let value):
          // 解析返回的文本数据
          let pattern = "\"([^\"]+)\""
          do {
            let regex = try NSRegularExpression(pattern: pattern)
            let matches = regex.matches(in: value, range: NSRange(location: 0, length: value.count))

            var suggestions: [String] = []
            matches.forEach { match in
              if let range = Range(match.range(at: 1), in: value) {
                let suggestion = String(value[range])
                suggestions.append(suggestion)
              }
            }
            // 处理解析后的结果
            if (andCallback != nil) {
              andCallback!(suggestions)
            }
          } catch {
            print("Regex matching failed: \(error)")
            if (andCallback != nil) {
              andCallback!([])
            }
          }
        case .failure(let error):
          // 在此处处理请求失败的情况
          print("Request failed: \(error)")
          if (andCallback != nil) {
            andCallback!([])
          }
        }
      }
    }
  }

  // 获取搜索词列表
  static func ht_searchHistoryList(callback: (([String]) -> Void)?) -> Thunk<HTAppState> {
    Thunk<HTAppState> { dispatch, _ in
      let var_history = HTCoreDataManager().ht_fetchSearchHistoryData()
      var var_historyStrs: [String] = []
      for history in var_history {
        var_historyStrs.append(history.string_name!)
      }

      if (callback != nil) {
        callback!(var_historyStrs)
      }

      dispatch(HTEnumSearchAction.htEnumSearchHistory(var_searchHistory: var_historyStrs))
    }
  }

  // 添加搜索词
  static func ht_addSearchHistory(name: String) -> Thunk<HTAppState> {
    Thunk<HTAppState> { dispatch, _ in
      HTCoreDataManager().ht_addNewSearchHistory(name: name)

      dispatch(ht_searchHistoryList(callback: nil))
    }
  }

  // 删除所有搜索词
  static func ht_deleteAllSearchHistory() -> Thunk<HTAppState> {
    Thunk<HTAppState> { dispatch, _ in
      HTCoreDataManager().ht_deleteAllSearchHistory()

      dispatch(ht_searchHistoryList(callback: nil))
    }
  }
}
